/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import app from '@system.app';
import prompt from '@system.prompt';
import state from '../../../../../js/share/js/login/state.js'
import {HuaweiIdAuthParamsHelper, HuaweiIdAuthManager} from '@hmscore/hms-jsb-account';
import faUtils from '../../../../../js/share/js/fa-utils.js'
import storage from '@system.storage';
import commonUtils from '../../../../../js/share/js/common-utils.js'
const showState = [state.connection.PRIVACY]
const JS_TAG = 'JS/Component/Login dialog: ';
import configuration from '@system.configuration';
export default {
    props: ['state'],
    data: {
        checked: false,
        version: '',
        showProgress: false
    },
    computed: {
        showObject() {
            return showState.indexOf(this.state) > -1;
        },
        checkboxIcon() {
            return this.checked ? this.$r('common.checked') : this.$r('common.unchecked')
        }
    },
    onInit() {
        console.debug(JS_TAG + 'onInit');
        this.version = app.getInfo().versionName;
        this.checkPrivacy();
        this.language=configuration.getLocale().language;
    },

    checkPrivacy: function () {
        faUtils.logInfo(JS_TAG + 'Checking privacy status')
        storage.get({
            key: 'privacy',
            success: data => {
                if (data == 'true') {
//                    this.checked = true
                    faUtils.logInfo(JS_TAG + 'Privacy has been agreed.')
                    this.$emit('onPrivacyAgreed');
                    this.notifyLogin()
                    // 如果用户之前已经同意隐私协议，则检查登录状态(静默登录)
                    this.checkLoginStatus();
                } else {
                    faUtils.logInfo(JS_TAG + 'Privacy is not agreed.');
                }
            },
            fail: (data, code) => {
                faUtils.logInfo(JS_TAG + 'Check privacy data failed, error code:' + code + ', data: ' + data);
            },
            complete: () => {
                faUtils.logInfo(JS_TAG + 'Check privacy finished');
            }
        });
    },
    // #.用户没有同意过隐私协议，手动点击卡片的登录按钮
    login() {
        this.$emit('onLoginSuccess')
//        const signInOption = new HuaweiIdAuthParamsHelper().setId().setProfile().setDialogAuth().build();
//        HuaweiIdAuthManager.getAuthApi().getSignInIntent(signInOption).then(res => {
//            faUtils.logInfo(`signIn success. ${JSON.stringify(res)}`);
//            this.agreePrivacy()
//            this.$emit('onLoginSuccess', res)
//        }).catch(error => {
//            faUtils.toast(error.errMsg)
//            faUtils.logError(`signIn fail. ${JSON.stringify(error)}`);
//            this.processLoginError()
//        });
    },

    notifyLogin() {
        this.$emit('onStartLogin');
    },

    // 2.如果用户同意隐私协议后，检查登录状态，执行静默登录
    checkLoginStatus() {
        this.notifyLogin()
        this.showProgress = true;
        faUtils.logInfo(JS_TAG + 'Check login status start');
        const signInOption = new HuaweiIdAuthParamsHelper().setId().setProfile().setDialogAuth().build();
        HuaweiIdAuthManager.getAuthApi().silentSignIn(signInOption).then(res => {
            faUtils.logInfo(`silentSignIn success. ${JSON.stringify(res)}`);
            this.$emit('onLoginSuccess', res)
        }).catch(error => {
            this.showProgress = false;
            faUtils.toast(error.errMsg)
            faUtils.logError(`silentSignIn fail. ${JSON.stringify(error)}`);
            this.processLoginError(error)
        });
        
    },

    // 4.用户同意隐私协议，存储同意状态
    agreePrivacy: function () {
        faUtils.logInfo(JS_TAG + 'Privacy agree is clicked, start saving privacy agree status.');
        storage.set({
            key: 'privacy',
            value: 'true',
            success: () => {
                faUtils.logInfo(JS_TAG + 'Privacy agree status is saved.')
            },
            fail: (data, code) => {
                faUtils.logError(JS_TAG + 'Save privacy agree status failed, error code:' + code + ', data: ' + data);
            },
            complete: () => {
                faUtils.logInfo(JS_TAG + 'Save privacy agree status finished.');
            }
        });
    },

    processLoginError(loginError) {
        if (loginError.errMsg) {
            prompt.showToast({
                message: this.$t(loginError.showMsg),
                duration: 5000
            });
        } else if (loginError.error_description) {
            prompt.showToast({
                message: loginError.error_description,
                duration: 5000
            });
        } else {
            prompt.showToast({
                message: this.$t('strings.public_system_error'),
                duration: 5000
            });
            console.error(JS_TAG + 'processLoginError, error = ' + JSON.stringify(loginError));
        }
        this.$emit('onLoginError', loginError);
    },
    onCheckboxChange() {
        this.checked = !this.checked;
    },
    openPrivacyDialog() {
        console.info(JS_TAG + 'openPrivacyDialog');
//        this.$emit('onPrivacyDisplay');
        let webUrl=this.language=='zh'?'http://www.baojudianshang.com/col.jsp?id=139':'http://www.baojudianshang.com/col.jsp?id=140'

        commonUtils.openUrl(webUrl);

    },
    exit() {
        app.terminate();
    },

}